package com.bupt.smart.ui.fragment;
import android.app.ListFragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Scroller;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.bupt.smart.model.Market;
import com.bupt.smart.network.APIManager;
import com.bupt.smart.ui.activity.MarketActivity;
import com.bupt.smart.ui.widget.ScrollerView;
import com.bupt.smart.utils.GeneratetoBitmap;
import com.bupt.smart.utils.JsonHelper;
import com.bupt.smart.utils.MarketHttpClient;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;
import com.bupt.smart.smart.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


import com.bupt.smart.ui.activity.MyListView;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.DefaultSliderView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.marshalchen.ultimaterecyclerview.expanx.Util.parent;


import org.json.JSONArray;
import org.json.*;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by wwl on 2016/3/25.
 */
public class MarketFragment extends Fragment {
    private SliderLayout mImageSlider;
    private ArrayList<String> imageUrls = new ArrayList<String>();
    private ArrayList<String> mini_list;
    private SimpleAdapter adapter;
    private MyListView lv;
    private View loading;
    private LinearLayout l;
    private Intent intent;
    private ArrayList<Map<String, Object>> list = new ArrayList<Map<String,Object>>();//填充listview
    private ScrollView scrollListview ;
    List<Market> list_marketinfo ;//存放商家信息
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        //获取后台商家信息数据：
        getDataFromDB();
        adapter = new SimpleAdapter(this.getActivity(),list,R.layout.market_list,
                new String[]{"marketname","marketyouhui","img","ID"},//market:商家名称   info:商家信息   img:商家图片
                new int[]{R.id.market,R.id.info,R.id.img,R.id.marketID});
        //不使用本地图片资源，使用后台图片数据
        adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
            @Override
            public boolean setViewValue(View view, Object data, String textRepresentation) {
                if (data instanceof Bitmap && view instanceof ImageView) {
                    ImageView i = (ImageView) view;
                    i.setImageBitmap((Bitmap) data);
                    return true;
                }
                return false;
            }
        });

    }
    /*
    * 1 配置ListView 的 adapter
    * 2 页面跳转传递数据
    * */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mini_list = new ArrayList<String>(); //实例化mini_list
        View v = inflater.inflate(R.layout.market_fragment, null);
        //滚动条
        mImageSlider = (SliderLayout) v.findViewById(R.id.img_slider);
        mImageSlider.setPresetTransformer(SliderLayout.Transformer.Accordion);
        mImageSlider.setIndicatorVisibility(PagerIndicator.IndicatorVisibility.Invisible);
        mImageSlider.setCustomAnimation(new DescriptionAnimation());
        mImageSlider.setDuration(3000);
        scrollListview = (ScrollView)v.findViewById(R.id.scListview);
        lv = (MyListView)v.findViewById(R.id.lv);
        lv.setAdapter(adapter);
        loading = (View)v.findViewById(R.id.loading);
        InitImage();
        InitFlashView();
        return v;
    }
    /*
    * author:wwl
    * 2016/05/13
    * 连接后台获取商家信息
    *
    * */
    public void getDataFromDB(){
        Call<List<Market>> call = APIManager.getMarketAPI().getMarketInfo();
        call.enqueue(new Callback<List<Market>>() {
            @Override
            public void onResponse(Call<List<Market>> call, Response<List<Market>> response) {
                Log.i("resp",response.body().get(0).getID()+"");
                if(response.body()!=null) {
                    list_marketinfo = response.body();
                    Map<String, Object> map = null;
                    for(int i=0;i<list_marketinfo.size();i++){
                        map = JsonHelper.Bean2Map(list_marketinfo.get(i));
                        map.put("img",GeneratetoBitmap.GenerateImage((String)map.get("marketimg_str")));//将img_str转成bitmap
                        Log.i("marketid",list_marketinfo.get(i).getID()+"");
                        list.add(map);//Market -> map<String,Object>
                    }
                    adapter.notifyDataSetChanged();
                    lv.setAdapter(adapter);
                    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            Intent intent = new Intent(getActivity(), MarketActivity.class);
                            intent.putExtra("market",list_marketinfo.get(position));
                            getActivity().startActivity(intent);
                        }
                    });
                    scrollListview.setVisibility(View.VISIBLE);
                    loading.setVisibility(View.GONE);
                }

            }

            @Override
            public void onFailure(Call<List<Market>> call, Throwable t) {
                Toast toast = Toast.makeText(getContext(),"请检查网络连接...",Toast.LENGTH_SHORT);
                toast.show();
            }
        });
    }


    /*
    * 轮播图片
    *
    * */
    public void InitFlashView(){
        for(String url : imageUrls) {
            DefaultSliderView defaultSliderView = new DefaultSliderView(getActivity());
            defaultSliderView
                    .image(url)
                    .setScaleType(BaseSliderView.ScaleType.Fit);
            mImageSlider.addSlider(defaultSliderView);
        }
    }
    public void InitImage(){
        imageUrls.add("http://p0.meituan.net/460.280/deal/3a630f84ec92ff166bf21d386bfddbae195023.jpg@PC");
        imageUrls.add("http://f.hiphotos.baidu.com/lbs/pic/item/30adcbef76094b363129fc07a5cc7cd98c109da5.jpg");
        imageUrls.add("http://a.hiphotos.baidu.com/lbs/pic/item/d8f9d72a6059252d645db2b9339b033b5ab5b9c1.jpg");
    }
}
